const { defineConfig } = require("@rspack/cli");
const { rspack } = require("@rspack/core");
const { resolve } = require("path");
// const { ErudaPlugin } = require("rspack-plugin-eruda");
const RefreshPlugin = require("@rspack/plugin-react-refresh");
const { ErudaPlugin } = require("../dist/index.js");
// const ErudaPlugin = require("../dist/index.js");
// const { ErudaPlugin } = require("./eruda-plugin");
const isDev = process.env.NODE_ENV === "development";
const isCordova = process.env.REACT_APP_CORDOVA || "false";
const isDebug = process.env.REACT_APP_ENV === "prod";
console.log(ErudaPlugin);
// Target browsers, see: https://github.com/browserslist/browserslist
const targets = ["chrome >= 87", "edge >= 88", "firefox >= 78", "safari >= 14"];

const getCssLoader = () => ({
  loader: "builtin:lightningcss-loader",
  options: {
    targets,
  },
});

const getPostcssLoader = () => ({
  loader: "postcss-loader",
  options: {
    postcssOptions: {
      plugins: [
        "tailwindcss",
        [
          "postcss-pxtorem",
          {
            rootValue: 37.5,
            minPixelValue: 1.000001,
            propList: ["*"],
            exclude: /node_modules/i,
          },
        ],
      ],
    },
    cache: true,
  },
});

const getLessLoader = () => ({
  loader: "less-loader",
  options: {
    lessOptions: {
      modifyVars: {
        "@base-font-size": 37.5,
        "@color-primary": "#FBAA19",
        "@color-danger": "#B91C1C",
      },
      javascriptEnabled: true,
    },
  },
});

const getSassLoader = () => ({
  loader: "sass-loader",
});

const getBabelImport = () => {
  return [
    {
      libraryName: "ahooks",
      libraryDirectory: "es",
      camelToDashComponentName: false,
    },
    {
      libraryName: "lodash",
      camelToDashComponentName: false,
    },
    {
      libraryName: "antd-mobile",
      libraryDirectory: "es/components",
      style: false,
    },
    {
      libraryName: "@fexd/tools",
      libraryDirectory: "es",
      camelToDashComponentName: false,
    },
    {
      libraryName: "@fexd/mobile",
      libraryDirectory: "es/exports",
      camelToDashComponentName: false,
      style: "{{member}}/style.less",
    },
    {
      libraryName: "@fexd/mobile-router5",
      libraryDirectory: "es/exports",
      camelToDashComponentName: false,
      style: "{{member}}/style.less",
    },
  ];
};

module.exports = defineConfig({
  context: __dirname,
  devServer: {
    // open: true,
    port: 8889,
    server: "https",
    proxy: [
      {
        context: ["/papi"],
        target: "https://test-loan.paypaya.com",
        secure: false,
        changeOrigin: true,
        cookieDomainRewrite: "0.0.0.0",
        logLevel: "silent",
      },
      {
        context: ["/uapi"],
        target: "https://test-loan.paypaya.com",
        secure: false,
        changeOrigin: true,
        cookieDomainRewrite: "0.0.0.0",
        logLevel: "silent",
      },
      {
        context: ["/frontline"],
        target: "https://test-riki.akulaku.com",
        secure: false,
        changeOrigin: true,
        cookieDomainRewrite: "0.0.0.0",
        logLevel: "silent",
      },
      {
        context: ["/iki"],
        target: "https://test-loan.paypaya.com/",
        secure: false,
        changeOrigin: true,
        cookieDomainRewrite: "0.0.0.0",
        logLevel: "silent",
      },
    ],
  },
  devtool: isDev ? "eval-cheap-module-source-map" : false,
  ignoreWarnings: [/WARNING\sin\svendors\.css/, () => true],
  resolve: {
    alias: {
      "@": resolve(__dirname, "./src"),
      "~@": resolve(__dirname, "./src"),
      "react/jsx-runtime": "react/jsx-runtime.js",
    },
    extensions: [
      ".ts",
      ".tsx",
      ".js",
      ".jsx",
      ".json",
      ".less",
      ".scss",
      ".css",
      ".mjs",
      ".md",
      ".pdf",
    ],
    modules: [resolve(__dirname, "src"), "node_modules"],
    symlinks: false,
  },
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif|webp|avif|svg)$/,
        exclude: /node_modules/,
        type: "asset/resource",
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf|pdf)$/,
        exclude: /node_modules/,
        type: "asset",
      },
      {
        test: /\.md$/,
        exclude: /node_modules/,
        use: ["html-loader", "markdown-loader"],
      },
      {
        test: /\.css$/,
        type: "css/auto",
        use: [getCssLoader(), getPostcssLoader()],
      },
      {
        test: /\.(sass|scss)$/,
        type: "css/auto",
        use: [getCssLoader(), getPostcssLoader(), getSassLoader()],
      },
      {
        test: /\.less$/,
        type: "css/auto",
        use: [getCssLoader(), getPostcssLoader(), getLessLoader()],
      },
      {
        test: /[\\/]node_modules[\\/]@fexd(?:\/.+)?[\\/].*\.(js|jsx|ts|tsx|less|css|scss|sass)$/,
        sideEffects: true,
      },
      {
        test: /\.(js?|jsx?|ts?|tsx?)$/,
        exclude: /node_modules/,
        use: [
          {
            loader: "builtin:swc-loader",
            options: {
              env: {
                targets,
              },
              jsc: {
                parser: {
                  syntax: "typescript",
                  tsx: true,
                },
                transform: {
                  react: {
                    runtime: "automatic",
                    development: isDev,
                    refresh: isDev,
                  },
                },
                experimental: {
                  // plugins: [
                  //   [
                  //     "swc-plugin-jsx-css-modules",
                  //     {
                  //       prefer: "local",
                  //       styleFileReg: ["\\.module\\.(css|scss|sass|less)$"],
                  //       importStyle: "namespace",
                  //     },
                  //   ],
                  // ],
                },
              },
              rspackExperiments: {
                import: getBabelImport(),
              },
            },
          },
        ],
      },
    ],
  },
  plugins: [
    isDev ? new RefreshPlugin() : null,
    new rspack.DefinePlugin({
      "process.env": JSON.stringify(process.env),
    }),
    new rspack.HtmlRspackPlugin({
      minify: !isDev,
      inject: true,
      template: resolve(__dirname, "public/index.html"),
      templateParameters: {
        PUBLIC_URL: "",
        REACT_APP_CORDOVA: isCordova,
      },
    }),
    new ErudaPlugin({
      debug: true,
    }),
  ].filter(Boolean),
  cache: true,
  experiments: {
    css: true,
  },
  optimization: {
    minimize: !isDev,
    usedExports: true,
    minimizer: [
      new rspack.SwcJsMinimizerRspackPlugin({
        minimizerOptions: {
          compress: true,
          mangle: true,
        },
      }),
      new rspack.LightningCssMinimizerRspackPlugin({
        minimizerOptions: { targets },
      }),
    ],
    moduleIds: "deterministic",
    chunkIds: "deterministic",
    splitChunks: {
      chunks: "all",
      maxInitialRequests: 6,
      maxAsyncRequests: 10,
      cacheGroups: {
        vendors: {
          name: "vendors",
          test: /[\\/]node_modules[\\/]/,
          chunks: "all",
          priority: -10,
          reuseExistingChunk: true,
          minSize: 30000,
          maxSize: 250000,
        },
        common: {
          name: "common",
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true,
        },
        styles: {
          name: "styles",
          test: /\.(css|less|scss|sass)$/,
          chunks: "all",
          enforce: true,
          priority: 20,
          reuseExistingChunk: true,
        },
      },
    },
    runtimeChunk: {
      name: "runtime",
    },
  },
  output: {
    path: resolve(__dirname, "build"),
  },
});
